<script setup lang="ts">
  import { ref } from 'vue'
  import { getGoodsListApi } from '@/api/goods'
  import type { goodsListItem } from '@/types/goods'
  // 必须导入需要用到的页面生命周期（即使在当前页面上没有直接使用到）
  import { onLoad, onPageScroll, onReachBottom } from '@dcloudio/uni-app'
  import useZPaging from '@/uni_modules/z-paging/components/z-paging/js/hooks/useZPaging.js'
  import useZPagingComp from '@/uni_modules/z-paging/components/z-paging/js/hooks/useZPagingComp.js'
  import { fullUrl, computeConversion } from '@/utils/common'
  import { pageUrl } from '@/utils/constants'
  import { VoteApi } from '@/api/home'
  import { forEach } from 'lodash'
  import { getVoteListApi } from '@/api/home'
  // import qqMapWx from '@/utils/qqmap-wx-jssdk.min.js'
  // import qqmapsdk from "@/utils/qqmap-wx-jssdk.min.js"
  const paging = ref()
  const dataList = ref<goodsListItem[]>([])
  // 类似mixins，如果是页面滚动务必要写这一行，并传入当前ref绑定的paging，注意此处是paging，而非paging.value
  useZPaging(paging)

  const props = withDefaults(
    defineProps<{
      query ?: any
      safeAreaInsetBottom ?: boolean
      options ?: any

    }>(),
    {
      query: () => [],
      safeAreaInsetBottom: false,

    },
  )

  const query = ref(props.query)

  const queryList = (page : number, page_size : number) => {
    const params = {
      page,
      page_size,
      ...query.value,
    }

    getGoodsListApi(params).then((res) => {
      paging.value.complete(res.result.data)
    })
  }
  // 投票列表
  const votesList:any = ref([])
  const page = ref(1)
  const limit = ref(10)
  const getVotesList = async(type_id:number = 1) => {
    const data = {
      vote_type_id: type_id,
      page: page.value,
      limit: limit.value
    }
    const res = await getVoteListApi(data)
    // console.log("res==", res)
    const temp:any = res.result
    // if (!Array.isArray(votesList.value)) {
    //   votesList.value = []; // 如果不是数组，则重置为数组
    // }
    // votesList.value = [...votesList.value, ...temp.data];
    votesList.value = temp.data
  }

  onLoad(()=>{
    getVotesList()
  })

  const reload = () => {
    return paging.value.reload()
  }

  const refresh = () => {
    return paging.value.refresh()
  }

  const emits = defineEmits<{
    (e : 'refresher-status-changed', status : number) : void
  }>()

  const onRefresherStatusChange = (status : number) => {
    emits('refresher-status-changed', status)
  }

  defineExpose({ ...useZPagingComp(paging), reload, refresh })

  const doVote = async (id : number) => {
    const data = {
      id: id
    }
    console.log(data)
    const res = await VoteApi(data)
    console.log(res)
    if (res.code === 200) {
      uni.showToast({
        title: '投票成功',
        duration: 1000
      });
      window.location.reload()
    }

  }

  const navTo = (item : any) => {


    uni.openLocation({
      latitude: Number(item.lat), // 纬度
      longitude: Number(item.lng),
      scale: 18, // 缩放级别，5~18
      name: item.name, // 位置名
      address: item.address, // 地址详情说明
      success: function () {
        console.log('导航成功');
      },
      fail: function (err) {
        console.error('导航失败', err);
      }
    });

  }

  const tabIndex = ref(1)
  const tabsInfo = ref([
    {
      id: 1,
      name: '苗王争霸赛',
      status: true
    },
    {
      id: 2,
      name: '人气王',
      status: false
    },
    {
      id: 3,
      name: '粮王争霸赛',
      status: false
    }
  ])

  const changeTabsIndex = (id : number) => {
    tabsInfo.value.forEach((item) => {
      if (item.id == id) {
        tabIndex.value = id
        getVotesList(id)
      }
    })
  }

  const goNextPage = (url: string) => {
    uni.navigateTo({
      url: url
    })
  }

  const goVoteDetail = (id: number) => {
    uni.navigateTo({
      url: "/pages/index/vote_detail/vote_detail?id=" + id
    })
  }

</script>

<template>

  <z-paging ref="paging" v-model="dataList" @query="queryList" :safe-area-inset-bottom="props.safeAreaInsetBottom"
    @refresherStatusChange="onRefresherStatusChange" v-bind="props.options" :paging-style="{
      backGroundColor: '#fff',
    }">
    <template #top>
      <slot name="top"></slot>
    </template>
    <slot name="middle"></slot>

    <view class="vote-tabs">
      <block v-for="item in tabsInfo" :key="item.id">
        <view :class="item.id==tabIndex ? 'active': 'tabs-item'" @click="changeTabsIndex(item.id)">{{item.name}}</view>
      </block>
    </view>
    <view class="votes-container">

      <view class="votes" v-for="item in votesList" :key="item.id">
        <view class="num">{{item.num}} 票</view>
        <view class="content" style="width: 100%;">
          <view class="content-img" @click="goVoteDetail(item.id)">
            <image class="image" mode="aspectFill" :src="fullUrl(item.images[0])"></image>
          </view>
          <view class="content-text" @click="goVoteDetail(item.id)">
            <view class="title">{{item.title}}</view>
            <view class="text-item" style="justify-content: flex-start">
              <uni-icons type="flag" size="30"></uni-icons>
              <text>{{item.titles}}</text>
            </view>
            <view class="text-item" style="justify-content: flex-start">
              <uni-icons type="location" size="30"></uni-icons>
              <text>{{item.titless}}</text>
            </view>
          </view>
          <view class="content-footer">
            <text @click="navTo(item)" class="nav">导航</text>
            <text @click="goVoteDetail(item.id)" class="nav2">投票</text>

          </view>
        </view>
      </view>
    </view>

    <view class="list">
      <!-- <navigator
        class="list-item"
        v-for="item in dataList"
        :key="item.id"
        :url="`${pageUrl['goods-detail']}?id=${item.id}`"
      >
        <image class="image" mode="scaleToFill" :src="fullUrl(item.images[0])"></image>
        <view class="list-item-detail">
          <view class="name"> {{ item.name }} </view>
          <view class="price">
            <text class="small">¥</text>
            <text class="price-now">{{ item.min_price }}</text>
            <text class="price-origin">{{ item.max_origin_price }}</text>
          </view>
          <view class="sale">
            <text>销量{{ computeConversion(item.total_sales) }}</text>
          </view>
        </view>
      </navigator> -->
    </view>
  </z-paging>
</template>

<style lang="scss" scoped>
  :host {
    display: block;
  }

  .vote-tabs {
    display: flex;
    justify-content: space-around;
    align-items: center;
    margin-top: 20rpx;
    min-height: 60rpx;

    .tabs-item {
      background-image: linear-gradient(to bottom right, #01B468, #4EFEB3);
      border: 2rpx solid #4EFEB3;
      border-bottom-left-radius: 40rpx;
      border-top-right-radius: 40rpx;
      padding: 15rpx 30rpx;
      width: 30%;
      text-align: center;
      font-size: 26rpx;
      font-weight: bold;

    }

    .active {
      background-image: linear-gradient(to bottom right, #01B468, #4EFEB3);
      color: #fff;
      border-bottom-left-radius: 40rpx;
      border-top-right-radius: 40rpx;
      padding: 15rpx 30rpx;
      width: 30%;
      text-align: center;
      font-size: 26rpx;
      font-weight: bold;
      border: 2rpx solid #4EFEB3;
    }
  }

  .votes-container {
    display: flex;
    justify-content: space-between;
    // align-items: center;
    flex-wrap: wrap;
    width: 100%;
    .votes {
      display: flex;
      flex-direction: column;
      // justify-content:
      align-items: center;
      /* 确保内容从顶部开始对齐 */
      position: relative;
      /* 使其子元素可以相对它定位 */
      background-color: #E4FDF0;
      width: 46%;
      border-radius: 30rpx;
      margin-top: 20rpx;
      margin-left: 15rpx;
      margin-right: 15rpx;

      .content {
        display: flex;
        flex-direction: column;
        justify-content: flex-start;

        .content-img {
          image {
            border-top-right-radius: 30rpx;
            border-top-left-radius: 30rpx;
            width: 100%;
            height: 400rpx;
            max-height: 400rpx;
            // width: auto;
            // overflow: hidden;
          }

          // object-fit: cover;
          // overflow: hidden;
          // width: 100%;
          // background-color: #262626;
        }

        .content-text {
          display: flex;
          flex-direction: column;
          justify-content: space-between;
          padding: 10rpx;
          // font-size: 30rpx;
          line-height: 40rpx;
          .title {
            font-size: 32rpx;
            font-weight: bold;
            margin: 20rpx 0;
          }
          .text-item {
            display: flex;
            flex-direction: row;
            justify-content: space-between;
            margin: 10rpx 0;
            font-size: 24rpx;
            color: #666666;

          }
        }

        .content-footer {
          display: flex;
          align-items: center;
          justify-content: space-around;
          margin: 20rpx 0;

          .nav {
            min-width: 80rpx;
            background-color: #fff;
            color: green;
            padding: 5rpx 10rpx;
            border-radius: 25rpx;
            text-align: center;
            border: green 2rpx solid;
          }

          .nav2 {
            margin-left: 20rpx;
            min-width: 80rpx;
            background-color: green;
            color: #fff;
            padding: 5rpx 10rpx;
            border-radius: 25rpx;
            text-align: center;
            border: green 2rpx solid;
          }

        }
      }

      .num {
        color: #262626;
        font-size: 35rpx;
        position: absolute;
        /* 绝对定位 */
        top: 0;
        /* 距离顶部 0 */
        left: 0;
        /* 距离左边 0 */
        background-color: rgba(217, 251, 181, 1);
        /* 可选：增加背景色并设置透明度，使数字更易读 */
        padding: 5px 10px;
        /* 可选：增加内边距 */
        z-index: 1;
        /* 确保它位于内容上方 */
        border-bottom-right-radius: 30rpx;
      }
    }

  }

  .list {
    display: flex;
    flex-wrap: wrap;
    justify-content: space-between;
    padding: 0 5rpx;

    .list-item {
      width: calc(50vw - 10rpx);
      margin-bottom: 10rpx;
      border-radius: 10rpx;
      overflow: hidden;
      background-color: #fff;
    }

    .list-item-detail {
      padding: 10rpx 10rpx 20rpx;
    }

    .image {
      height: 320rpx;
      width: 100%;
    }

    .name {
      margin: 10rpx 0 10rpx;
      font-size: 26rpx;
      color: #262626;
      min-height: 70rpx;
      line-height: 1.4;
      max-height: calc(2 * 1.4 * 26rpx);
      overflow: hidden;
      text-overflow: ellipsis;
      display: -webkit-box;
      -webkit-line-clamp: 2;
      -webkit-box-orient: vertical;
    }

    .price {
      line-height: 1;
      padding-top: 4rpx;
      color: #cf4444;
      font-size: 26rpx;

      &-origin {
        font-size: 20rpx;
        color: #999;
        text-decoration: line-through;
        margin-left: 10rpx;
      }
    }

    .small {
      font-size: 80%;
    }

    .sale {
      display: flex;
      justify-content: flex-end;
      padding-top: 20rpx;
      font-size: 20rpx;
      color: #666666;
    }
  }
</style>
